package com.lenovo.dh.voteclient;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.lenovo.dh.voteclient.bean.Topics.Topic;
import com.lenovo.dh.voteclient.service.Contans;
import com.lenovo.dh.voteclient.service.ServiceHandler;
import com.lenovo.dh.voteclient.service.VoteService;
import com.lenovo.dh.voteclient.utils.Utils;

/**
 * A placeholder fragment containing a simple view.
 */
public class PlaceholderFragmentEx extends Fragment implements View.OnClickListener,Contans,ServiceHandler{
	Button commitButton;
	Button nextTopicButton;
	RadioGroup optionsRadio;
	VoteService service;
	TextView currentTopicTitle;
	Topic currentTopic;
	View rootView;
	TextView errorText;
	private BroadcastReceiver downloadReceiver;
	Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case MSG_LOAD_FINISH:
				currentTopic = (Topic) msg.obj;
				refreshCurrentTopic();
				break;

			default:
				break;
			}
		};
	};
	
	public PlaceholderFragmentEx() {
		
	}
	@Override
	public void onStart() {
		service = new VoteService(getActivity());
		service.registerCallback(this);
		registerReceiver();
		super.onStart();
	}
	@Override
	public void onStop() {
		service.unRegisterCallback(this);
		unregisterReceiver();
		super.onStop();
	}
	private void registerReceiver() {
		downloadReceiver = new DownloadReceiver();
		IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
//		intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
		getActivity().registerReceiver(downloadReceiver, intentFilter);
	}
	
	public void unregisterReceiver() {
		try {
			if(downloadReceiver != null) {
				getActivity().unregisterReceiver(downloadReceiver);
			}
		} catch (Exception e) {
			Log.d("shiqc1", "unregisterReceiver error....but is a liite error....you need do nothing");
//			e.printStackTrace();
		}
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		rootView = inflater.inflate(R.layout.fragment_main_ex, container, false);
		commitButton = (Button) rootView.findViewById(R.id.id_btn_commit);
		nextTopicButton = (Button) rootView.findViewById(R.id.id_btn_nextTopic);
		optionsRadio = (RadioGroup) rootView.findViewById(R.id.current_topic_options);
		currentTopicTitle = (TextView) rootView.findViewById(R.id.current_topic_title);
		errorText = (TextView) rootView.findViewById(R.id.detail_error);
		commitButton.setOnClickListener(this);
		nextTopicButton.setOnClickListener(this);
		return rootView;
	}
	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
	}

	@Override
	public void onResume() {
		service.exceLoadCurrentTopic();
		super.onResume();
	}
	private void refreshCurrentTopic() {
		Log.d("shiqc1", "refreshCurrentTopic.....");
		rootView.setVisibility(View.VISIBLE);
		errorText.setVisibility(View.INVISIBLE);
		currentTopicTitle.setText(currentTopic.getTitle());
		optionsRadio.removeAllViews();
		optionsRadio.clearCheck();
		for(int i = 0 ;i < currentTopic.options.size(); i++) {
			RadioButton btn = new RadioButton(getActivity());
			btn.setText(currentTopic.options.get(i).name);
			btn.setTextSize(20);
			btn.setId(currentTopic.options.get(i).id);
			btn.setButtonDrawable(R.drawable.radio);
			RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(RadioGroup.LayoutParams.WRAP_CONTENT, RadioGroup.LayoutParams.WRAP_CONTENT);
			params.setMargins(0,Utils.dip2px(getActivity(), 10), 0, 0);
			btn.setPadding(Utils.dip2px(getActivity(), 30),0 ,0,0);
			btn.setLayoutParams(params);
			optionsRadio.addView(btn);
		}
		if(optionsRadio.getChildCount() < 1 ) {
			errorText.setVisibility(View.VISIBLE);
		}
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.id_btn_commit:
			if(optionsRadio.getChildCount() < 1) {
				Toast.makeText(getActivity(), R.string.error, 1).show();
				return;
			}
			int currentOptionId = optionsRadio.getCheckedRadioButtonId();
			if(currentOptionId == -1) {
				Toast.makeText(getActivity(), R.string.commit_error_msg, 1).show();
				return;
			}
			service.exceCommitCurrentTopic(currentOptionId, currentTopic.getId(),Utils.getIME(getActivity())
						, Utils.getNameByShare(getActivity()));
			break;
		case R.id.id_btn_nextTopic:
			service.exceLoadCurrentTopic();
			break;

		default:
			break;
		}
	}
	public Handler getHandler() {
		return handler;
	}
	class DownloadReceiver extends BroadcastReceiver {

		public static final String TAG = "DownloadReceiver";

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			Log.d(TAG, "onReceive...action:" + action);
			if(ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE.equals(action)) {
				
			} else if(ConnectivityManager.CONNECTIVITY_ACTION.equals(action)) {
				if(service.checkNetworkStatus()) {
					service.exceLoadCurrentTopic();
				} else {
					Toast.makeText(getActivity(), R.string.net_error, 1).show();
				}
			} else if(WifiManager.RSSI_CHANGED_ACTION.equals(action)) {
//				startDownloadAdBoot();
			}
		}

	}
	
}